<template>
    <div id="comp-table-boxx">
        <a-table
        size="middle"
        :scroll="scrollTrigger"
        @change="changePagination"
        ref="compTableRef"
        :columns="columnsData"
        :dataSource="dataSource"
        :bordered="!config.bordered?true:config.bordered"
        :rowKey="config.rowKey"
        :size="tableSize"
        :loading="!isDataLoaded"
        :id="compTableId"
        :rowSelection="{...rowSelection, onChange:onChange, onSelectAll:onSelectAll, onSelect:onSelect}"
        :pagination="pagination"
        >
            <!-- <template v-for="(item, num) in scopedSlots" :slot="item" slot-scope="text, record" >
                {{ record }}
            </template> -->
            <template v-for="(item, num) in scopedSlots" :slot="item.customRender" slot-scope="text, record" >
                <slot :name="item.customRender" :record="[record]">
                </slot>
            </template>

        </a-table>
    </div>
</template>
<script>
import { config } from 'process';
import { axios } from '@/utils/request'
import { timingSafeEqual } from 'crypto';
export default {
    name:'compTablle',
    components:{},
    props:{
        config:{
            type:Object,
            required: true
        },
        columns:{
            type:Array,
            required: true
        },
        toBoolean: {
            // 把配置的值 转为 boolean
            type: Object,
            default: () => {
                return {
                isFalse: ['0', 'n', 'N', 0],
                isTrue: ['1', 'y', 'Y', 1]
                };
            },
            required: false
        },
        serverSorter: {//后端排序
            type: Boolean,
            default: true,
            required: false
        },
        showIndex: {
            // 是否显示索引
            type: Boolean,
            default: false,
            required: false
        },
        requestParamObj:{
            default: {},
            required: false
        }
    },
    data(){
        let _this = this
        return{
            compTableId:'compTableId'+new Date().getTime(),
            dataSource:[],//列表数据，要从传过来的接口拿
            bordered:false,
            rowKey:this.config.rowKey,
            tableSize:this.config.tableSize?this.config.tableSize:'default',//default | middle | small
            isDataLoaded:true,//数据请求是否完成？
            requestParam:this.config.requestParam || this.requestParamObj?{...this.config.requestParam,...this.requestParamObj}:{},
            rowSelection:{//单选或多选，
                tyep:this.config.rowSelection.type?this.config.rowSelection.type:'checkbox',//checkbox | radio
                selectedRowKeys:this.config.selectedRowKeys?this.config.selectedRowKeys:[],//默认选中项
                selectedRowNameS:this.config.selectedRowNameS?this.config.selectedRowNameS:[],//默认选中项
                
            },
            pagination:{
                position:'bottom',//指定分页显示的位置 'top' | 'bottom' | 'both'
                pageSize: 30,
                current: 1,
                total: 0,
                showTotal: (total, range) => {
                    // return this.$t('m.common.label.page_total', [range[0], range[1], total])
                    return range[0] + "-" + range[1] + " 共" + total + "条"
                },
                showSizeChanger: true,
                showQuickJumper:true,
                pageSizeOptions: ['10', '30', '50', '100','200','500','1000'],
                showLessItems:true,
                ...this.config.pagination
            },
            scopedSlots:[],
            isBoolean:[],
            scrollTrigger:{},
            columnsData:this.columns.map(item=>{return{width:item.width?item.width:129,...item,ellipsis:true}}),
        }
    },
    mounted(){
        //console.log('this.config',this.config)
        if (this.showIndex) {
            // 处理索引序号
            const hasIndex = this.columns.find((item) => item.scopedSlots.customRender === '_indexed');
            if (!hasIndex) {
                columns.unshift({
                title: '序号',
                dataIndex: 'id',
                width: 48,
                scopedSlots: {customRender: '_indexed'}
                });
            }
        }
        this.columns.forEach((item) => {
            //console.log(item)
            item.scopedSlots && this.scopedSlots.push(item.scopedSlots);
            item.isBoolean && item.key && this.isBoolean.push(item.key);
        });
        //console.log('this.scopedSlots',this.scopedSlots)
        this.getData(this.requestParam, this.pagination.current);
    },
    watch:{
        requestParamObj(newval,oldVal){
             this.getData(newval, this.pagination.current)
            //console.log('有没有改变===================',newval,oldVal)
        },
        // columns(newval,oldVal){
        //     this.columnsData = newval.map(item=>{return{...item,width:item.width?item.width:150}})
        // },
      
    },
    created() {
      // 该方法触发屏幕自适应
      this.resetScreenSize();
    },
    methods:{
        resetScreenSize() {
    
            let screenWidth = document.body.clientWidth;
            let screenHeigth = document.body.clientHeight;
            this.scrollTrigger = {x: screenWidth - 200,y:screenHeigth - 320}
            
            // 
            // if (screenWidth < 500) {
            // this.scrollTrigger = {x: 800};
            // } else {
            // this.scrollTrigger = {};
            // }
        },
        onChange(selectedRowKeys,selectedRows){
            //console.log('selectedRowKeys',selectedRowKeys)
            this.rowSelection.selectedRowKeys = selectedRowKeys
            this.$emit('selectedRowKeys',selectedRowKeys)

        },
        onSelectAll(selected,selectedRows,changeRows){

        },
        onSelect(record,selected,selectedRows){

        },
        async getData (params, currentPage = 1, sorter){
            return new Promise((resolve, reject) => {
                this.pagination.current = currentPage === 1 ? 1 : currentPage;
                this.isDataLoaded = false;
                const request = {
                    params: this.requestParamObj || {},
                    pageIndex: this.pagination.current, // 当前页
                    pageRows: this.pagination.pageSize
                };
                //console.log(11111,request)

                if (params) {
                    request.params = {
                        ...request.params,
                        ...params
                    };
                }
                //console.log('sorter',sorter)
                let sorterData = {}
                if(sorter){
                    if(this.serverSorter && sorter.field){
                        sorterData = {orderItem:sorter.columnKey,orderType:sorter.order}
                        this.$emit('sorterChange',sorterData,sorter)
                    }
                }
                
                this.requestParams = {...request.params,...this.requestParamObj,...sorterData}; // 存储查询参数
                // request.params = JSON.stringify(request.params);
                // debugger;
                axios({
                    url: this.config.api,
                    method:'get' ,
                    params: {
                        pageNo:request.pageIndex,
                        pageSize:request.pageRows,
                        ...params,
                        ...this.requestParamObj,
                        fywflcode:this.config.fywflcode,
                        ...sorterData,
                    },
                    url_1:'outside'
                }).then((res) => {
                    //console.log('列表######',res)
                    
                    if (res.code === 200) {
                        res.data = res.result.records
                        if (!Array.isArray(res.data)) {
                            res.data = [];
                        }
                        this.pagination.total = res.result.total || 0;

                        if (this.isBoolean.length) {
                            this.dataSource = res.data.map((item) => {
                                this.isBoolean.forEach((key) => {
                                if (this.toBoolean.isTrue.indexOf(item[key]) > -1) {
                                    item[key] = true;
                                } else if (this.toBoolean.isFalse.indexOf(item[key]) > -1) {
                                    item[key] = false;
                                }
                                });
                                return item;
                            });
                        } else {
                            this.dataSource = res.data;
                        }
                        // //console.log(state.data)
                    }
                    this.isDataLoaded = true; // 数据请求完成标识
                    // //console.log(res);

                    resolve(this.isDataLoaded);
                });
            });
        },
        //分页
        changePagination(pagination,filters,sorter){
            //console.log(pagination)
            this.pagination.pageSize = pagination.pageSize
            if (this.pagination.current === pagination.current) {
                // 点的是排序
                this.serverSorter && this.getData(undefined, pagination.current, sorter);
            } else {
                this.pagination.current = pagination.current;
                this.getData(undefined, pagination.current, sorter);
            }
        },
        reloadData () {//重新加载数据
            this.getData(undefined, 1);
        },

    }
}
</script>
<style lang="less">
#comp-table-boxx{
    overflow: auto;
    .ant-table-thead > tr >th{
        color: rgb(51,51,51)  !important;
        font-weight: 600 !important;   
        background: rgb(222, 229, 237) !important;
    }
    .ant-table td { white-space: nowrap !important; }

    .ant-table-tbody .ant-table-row td {
        padding-top: 0px;
        padding-bottom: 0px;
    }

    #components-layout-demo-custom-trigger .trigger {
        font-size: 18px;
        line-height: 64px;
        padding: 0 24px;
        cursor: pointer;
        transition: color .3s;
    }
}
</style>